//
//  GQHSuppliesController.m
//  Xanthium
//
//  Created by GuanQinghao on 17/03/2018.
//  Copyright © 2018 GuanQinghao. All rights reserved.
//

#pragma mark Macro
#import "GQHHeader.h"

#pragma mark Model
#import "GQHFreightModel.h"

#pragma mark Object

#pragma mark View
#import "GQHSuppliesView.h"

#pragma mark Controller
#import "GQHSuppliesController.h"
#import "GQHSupplyDetailController.h"
#import "GQHQutationDetailController.h"

#pragma mark CocoaPods

#pragma mark ----------Header End----------

@interface GQHSuppliesController () <GQHSuppliesViewDelegate>{
    
#pragma mark Data
    /// 请求参数
    NSMutableDictionary *parameters;
    /// 返回模型数组
    __block NSMutableArray<GQHFreightModel *> *freightModelArray;
#pragma mark View
    /// 自定义根视图
    GQHSuppliesView *rootView;
}

@end


@implementation GQHSuppliesController

#pragma mark --Lifecycle
- (void)loadView {
    DLog();
    
    rootView = [[GQHSuppliesView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    rootView.qh_delegate = self;
    self.view = rootView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    DLog();
    
    [self loadUserInterface];
    
    parameters = [NSMutableDictionary dictionary];
    [parameters setObject:USER_GET_ID forKey:@"releasePeople"];
    [parameters setObject:@"01" forKey:@"releaseState"];
    
    [self fetchServiceDataWithParameters:parameters];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    DLog();
    
    self.qh_rightButton.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    [rootView.qh_tableView.mj_header beginRefreshing];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    DLog();
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [rootView.qh_tableView.mj_header endRefreshing];
}

#pragma mark --Delegate
- (void)qh_onSaleOrNot:(UIButton *)sender {
    
    GQHFreightModel *freightModel = freightModelArray[sender.tag];
    NSMutableDictionary *para = [NSMutableDictionary dictionary];
    [para setObject:freightModel.qh_freightID forKey:@"sourcesId"];
    
    if ([freightModel.qh_state isEqualToString:@"01"]) {
        DLog(@"下架货源");
        
        NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buSources/1/soldOut"];
        [GQHNetHelper qh_requestGET:URLString parameters:para success:^(NSNumber *code, NSString *message, NSDictionary *data) {
            DLog(@"%@-%@",message,data);
            
            if (0 == [code intValue]) {
                
                [rootView.qh_tableView.mj_header beginRefreshing];
            } else {
                
                [self showToastWithText:message];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self qh_alertWithTitle:nil message:errorString actionTitle:nil handler:nil completion:nil];
        }];
    } else {
        DLog(@"重新发布");
        
        NSString *URLString = [[NSString qh_APIURLString] stringByAppendingString:@"/buSources/1/soldUp"];
        [GQHNetHelper qh_requestGET:URLString parameters:para success:^(NSNumber *code, NSString *message, NSDictionary *data) {
            DLog(@"%@-%@",message,data);
            
            if (0 == [code intValue]) {
                
                [rootView.qh_tableView.mj_header beginRefreshing];
            } else {
                
                [self showToastWithText:message];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self qh_alertWithTitle:nil message:errorString actionTitle:nil handler:nil completion:nil];
        }];
    }
}

- (void)qh_selectedRowWithTableView:(UITableView *)tableView atIndexPath:(NSIndexPath *)indexPath {
    
    ///titleArray = @[@"起始地",@"目的地",@"估算里程",@"货物名称",@"货物类型",@"货物重量",@"货物体积",@"货物数量",@"货物单价",@"需求车型",@"需求车长",@"装车时间",@"备注"];
    
    GQHFreightModel *freightModel = freightModelArray[indexPath.row];
    NSMutableArray *contentArray = [NSMutableArray array];
    
    [contentArray qh_safetySetObject:freightModel.qh_departure atIndex:0];
    [contentArray qh_safetySetObject:freightModel.qh_destination atIndex:1];
    
    NSString *mileage = freightModel.qh_mileage;
    [contentArray qh_safetySetObject:mileage atIndex:2];
    
    [contentArray qh_safetySetObject:freightModel.qh_freightName atIndex:3];
    [contentArray qh_safetySetObject:freightModel.qh_freightType atIndex:4];
    
    NSString *weight = [NSString stringWithFormat:@"%.0f",freightModel.qh_freightWeight];
    [contentArray qh_safetySetObject:weight atIndex:5];
    ///
    NSString *volume = [NSString stringWithFormat:@"%.0f",freightModel.qh_freightVolume];
    [contentArray qh_safetySetObject:volume atIndex:6];
    
    NSString *count = [NSString stringWithFormat:@"%.0f",freightModel.qh_freightNumber];
    [contentArray qh_safetySetObject:count atIndex:7];
    
    NSString *price = [NSString stringWithFormat:@"%.0f",freightModel.qh_freightUnitPrice];
    [contentArray qh_safetySetObject:price atIndex:8];
    
    [contentArray qh_safetySetObject:freightModel.qh_modelWanted atIndex:9];
    [contentArray qh_safetySetObject:freightModel.qh_lengthWanted atIndex:10];
    [contentArray qh_safetySetObject:freightModel.qh_loadingTime atIndex:11];
    [contentArray qh_safetySetObject:freightModel.qh_note atIndex:12];
    
    GQHSupplyDetailController *supplyDetailController = [[GQHSupplyDetailController alloc] init];
    supplyDetailController.qh_contentArray = contentArray;
    [self.navigationController pushViewController:supplyDetailController animated:YES];
}

- (void)qh_checkQutation:(UIButton *)sender {
    DLog(@"查看报价信息");
    
    GQHFreightModel *freightModel = freightModelArray[sender.tag];
    GQHQutationDetailController *qutationDetailController = [[GQHQutationDetailController alloc] init];
    qutationDetailController.qh_freightModel = freightModel;
    qutationDetailController.qh_state = freightModel.qh_state;
    qutationDetailController.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:qutationDetailController animated:YES];
}

#pragma mark --TargetMethod

#pragma mark --PrivateMethod
- (IBAction)changeSegmentIndex:(UISegmentedControl *)sender {
    DLog(@"改变索引");
    
    if (0 == sender.selectedSegmentIndex) {
        
        [parameters setObject:@"01" forKey:@"releaseState"];
        
        [self fetchServiceDataWithParameters:parameters];
        [rootView.qh_tableView.mj_header beginRefreshing];
        [rootView.qh_tableView.mj_header endRefreshing];
    } else {
        
        [parameters setObject:@"03" forKey:@"releaseState"];
        
        [self fetchServiceDataWithParameters:parameters];
        [rootView.qh_tableView.mj_header beginRefreshing];
        [rootView.qh_tableView.mj_header endRefreshing];
    }
}

- (void)fetchServiceDataWithParameters:(NSMutableDictionary *)parameters {
    
    __block int page = 1;
    
    [parameters setObject:ROWS forKey:@"rows"];
    
    rootView.qh_tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        page = 1;
        [parameters setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        
        [GQHFreightModel qh_fetchFreightsWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHFreightModel *> *freights) {
            
            if (status) {
                
                freightModelArray = [NSMutableArray arrayWithArray:freights];
                rootView.qh_freightModelArray = freightModelArray;
                [rootView.qh_tableView reloadData];
                
            } else {
                
                [self showToastWithText:message];
            }
            [rootView.qh_tableView.mj_header endRefreshing];
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_header endRefreshing];
        }];
    }];
    
    rootView.qh_tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        page++;
        [parameters setObject:[NSNumber numberWithInt:page] forKey:@"page"];
        
        [GQHFreightModel qh_fetchFreightsWithParameters:parameters success:^(BOOL status, NSNumber *code, NSString *message, NSArray<GQHFreightModel *> *freights) {
            
            if (status) {
                
                if (freights && freights.count > 0) {
                    
                    [freightModelArray addObjectsFromArray:freights];
                    rootView.qh_freightModelArray = freightModelArray;
                    [rootView.qh_tableView reloadData];
                    [rootView.qh_tableView.mj_footer endRefreshing];
                } else {
                    
                    [rootView.qh_tableView.mj_footer endRefreshingWithNoMoreData];
                }
            } else {
                
                [self showToastWithText:message];
                [rootView.qh_tableView.mj_footer endRefreshing];
            }
        } failure:^(NSError *error) {
            
            NSString *errorString = [NSString stringWithFormat:@"网络出错:%@,code:%ld", error.domain, (long)error.code];
            [self showToastWithText:errorString];
            [rootView.qh_tableView.mj_footer endRefreshing];
        }];
    }];
}

#pragma mark --Setter

#pragma mark --Getter

#pragma mark --View
- (void)loadUserInterface {
    
    NSArray *items = @[@"发布中",@"已下架"];
    UISegmentedControl *segmentControl = [[UISegmentedControl alloc] initWithItems:items];
    segmentControl.tintColor = kWhiteColor;
    segmentControl.selectedSegmentIndex = 0;
    
    NSMutableDictionary *normal = [NSMutableDictionary dictionary];
    [normal setValue:kDefaultFont forKey:NSFontAttributeName];
    [normal setValue:kWhiteColor forKey:NSForegroundColorAttributeName];
    [segmentControl setTitleTextAttributes:normal forState:UIControlStateNormal];
    
    NSMutableDictionary *highlighted = [NSMutableDictionary dictionary];
    [highlighted setValue:kDefaultFont forKey:NSFontAttributeName];
    [highlighted setValue:kAppRedColor forKey:NSForegroundColorAttributeName];
    [segmentControl setTitleTextAttributes:highlighted forState:UIControlStateHighlighted];
    
    [segmentControl addTarget:self action:@selector(changeSegmentIndex:) forControlEvents:UIControlEventValueChanged];
    [self.qh_titleLabel addSubview:segmentControl];
    self.qh_titleLabel.userInteractionEnabled = YES;
    [segmentControl mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(200);
        make.height.mas_equalTo(30);
        make.center.mas_equalTo(self.qh_titleLabel);
    }];
}

@end
